/**
 * Created by wangzilong on 2017/4/11.
 */
import React, { Component } from 'react';
import {
    AppRegistry,
    StyleSheet,
    Text,
    View,
    Image,
    ScrollView,
    TouchableOpacity,
    TextInput,
    ListView,
    Modal,
    Platform,
    InteractionManager,
    TouchableWithoutFeedback
} from 'react-native';
import ImageWrapper from '../components/ImageWrapper';
import NavigationBar from '../components/NavigationBar';
import userService from '../lib/services/userService';
var Dimensions = require('Dimensions');
const { width, height } = Dimensions.get('window');

export default class ClubMember extends Component{
    constructor(props) {
        super(props);
        var ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
        this.list = [];
        this.state = {
            memberList:ds.cloneWithRows(this.list),
            id:this.props.navigation.state.params.clubId,
            token:this.props.navigation.state.params.token,
            role:this.props.navigation.state.params.role,//群成员身份 0=》普通成员 1=》群主 2=》管理员
            groupName:this.props.navigation.state.params.groupName,
            groupUser:{},
            managerList:[],
            listStaturs:false,
            addManagerStaturs:false,//添加管理员
            deleteManager:false,//删除管理员
            deleteMember:false,//删除群成员
            addMember:false,//添加群成员
            modalVisible:false,
            allList:[],
            searchText:'',
        }; 
    }

    componentDidMount() {
        var $this = this;
        InteractionManager.runAfterInteractions(() => {
            $this.getMembers();
        });
    }

    renderModal(){
        if(this.state.role!=0){
            return(
                <Modal
                    transparent={true}
                    visible={this.state.modalVisible}
                    animationType={'slide'}
                    onRequestClose={()=>this.closeModal()}>
                    <TouchableWithoutFeedback onPress={()=>this.setState({modalVisible:false})}>
                        <View style={styles.modalBox}>
                            <View style={{padding:10}}>
                                {this.state.role==1?<TouchableOpacity onPress={()=>this.selectModal(1)} style={[styles.modalList,{borderTopLeftRadius:5,borderTopRightRadius:5}]}>
                                    <Text>添加管理员</Text>
                                </TouchableOpacity>:<View></View>}
                                {this.state.role==1?<TouchableOpacity onPress={()=>this.selectModal(2)} style={[styles.borderLine,styles.modalList,{borderTopWidth:1,borderTopColor:'#ccc'}]}>
                                    <Text>删除管理员</Text>
                                </TouchableOpacity>:<View></View>}
                                <TouchableOpacity onPress={()=>this.selectModal(3)} style={[styles.modalList,styles.borderLine]}>
                                    <Text>删除成员</Text>
                                </TouchableOpacity>
                                <TouchableOpacity onPress={()=>this.selectModal(4)} style={[styles.modalList,{borderBottomRightRadius:5,borderBottomLeftRadius:5}]}>
                                    <Text>添加成员</Text>
                                </TouchableOpacity>
                                <TouchableOpacity onPress={()=>this.selectModal(0)} style={[styles.modalList,{marginTop:10,borderRadius:5}]}>
                                    <Text>取消</Text>
                                </TouchableOpacity>
                            </View>
                        </View>
                    </TouchableWithoutFeedback>
                </Modal>
            )
        }
        
    }

    renderManager(){
        var list = this.state.managerList;
        return(
            list.map((item,i)=>{
                return(
                    <TouchableOpacity key={i} onPress={()=>this.goInformationDetails(item.user_id)}>
                        <View  style={{flexDirection:'row',alignItems:'center',backgroundColor:'#fff',borderBottomWidth:1,borderBottomColor:'#ddd'}}>
                            <MemberItem icon={{uri:'http://test.520m.com.cn/upload/thumb/'+item.imgs}} name={item.username} rank={item.grade}/>
                            {this.state.deleteManager?<TouchableOpacity onPress={()=>this.setManager(item.id,1,i)}>
                                <View style={{backgroundColor:'#FF0000',flex:1,alignItems:'center',justifyContent:'center',width:60}}>
                                    <Text style={{color:'#fff'}}>删除</Text>
                                </View>
                            </TouchableOpacity>:<View></View>}
                        </View>
                    </TouchableOpacity>
                )
            })
        )
    }

    renderItem(rowData, sectionID, rowID){
        // alert(JSON.stringify(rowData))
        // rowData.role  1群主2管理员 其他普通成员
        // <MemberItem icon={{uri:'http://test.520m.com.cn/upload/thumb/'+rowData.imgs}} iconRight={'touxiang'}  name={rowData.username} rank={rowData.grade}/>
        return(
            <TouchableOpacity onPress={()=>this.goInformationDetails(rowData.user_id)}>
                <View style={{flexDirection:'row',alignItems:'center',backgroundColor:'#fff',borderBottomWidth:1,borderBottomColor:'#ddd'}}>
                    {this.state.addManagerStaturs?<TouchableOpacity onPress={()=>this.setManager(rowData.id,1,rowID)}>
                        <View style={{paddingLeft:10}}>
                            <ImageWrapper icon={'addManager'}/>
                        </View>
                    </TouchableOpacity>:<View></View>}
                    <MemberItem icon={{uri:'http://test.520m.com.cn/upload/thumb/'+rowData.imgs}} name={rowData.username} rank={rowData.grade}/>
                    {this.state.deleteMember?<TouchableOpacity onPress={()=>this.setManager(rowData.id,2,rowID)}>
                        <View style={{backgroundColor:'#FF0000',flex:1,alignItems:'center',justifyContent:'center',width:60}}>
                            <Text style={{color:'#fff'}}>删除</Text>
                        </View>
                    </TouchableOpacity>:<View></View>}
                </View>
            </TouchableOpacity>
        )
    	
    }

    render(){
        return (
            <View style={styles.container}>
                {this.renderModal()}
                <NavigationBar 
                    leftIcon={'left'} 
                    titleText={'俱乐部成员列表'} 
                    leftPress={()=>this.goBack()}
                    rightText={this.state.role==0?'':'编辑'}
                    rightTextPress={()=>this.editList()}
                    rightTextStyle={{color:'#fff',fontSize:16}}/>
                <ScrollView>
                    <View style={{backgroundColor:'rgb(120,175,237)',padding:10}}>
                    	<TextInput 
                    		style={{backgroundColor:'#fff',paddingLeft:10,paddingRight:10,paddingTop:2,paddingBottom:2,borderRadius:2}}
                    		underlineColorAndroid={'transparent'}
                    		placeholder={'请输入成员名称'}
                            onChangeText={(text)=>this.searchMember(text)}
                            onEndEditing={()=>this.searchResult()}
                            returnKeyLabel={'搜索'}
                            returnKeyType={'搜索'}/>
                    </View>
                    {this.state.groupUser.username?<View>
                    	<View style={styles.listTitle}>
                    		<Text>创办人</Text>
                    	</View>
                    	<TouchableOpacity style={{flexDirection:'row'}} onPress={()=>this.goInformationDetails(this.state.groupUser.user_id)}>
                    		<MemberItem icon={this.state.groupUser.imgs?{uri:'http://test.520m.com.cn/upload/thumb/'+this.state.groupUser.imgs}:'touxiang'} name={this.state.groupUser.username || ''} rank={this.state.groupUser.grade || ''}/>
                    	</TouchableOpacity>
                    </View>:<View></View>}
                    {this.state.managerList.length>0?<View>
                        <View style={styles.listTitle}>
                            <Text>管理员</Text>
                        </View>
                        {this.renderManager()}
                    </View>:<View></View>}
                    {this.state.listStaturs?<View>
                    	<View style={styles.listTitle}>
                    		<Text>普通成员</Text>
                    	</View>
                    	<ListView
                    		dataSource={this.state.memberList}
                    		renderRow={(rowData,sectionID,rowID)=>this.renderItem(rowData,sectionID,rowID)}
                            enableEmptySections={true}/>
                	</View>:<View></View>}
                </ScrollView>
                
            </View>
        )

    }

    goBack(){
        this.props.navigation.goBack();
    }

    goInformationDetails(personId){
        var $this = this;
    	const {navigate} = this.props.navigation;
        navigate('InformationDetails',{personId:personId,token:$this.state.token})
    }

    goFriendsList(){
        var $this = this;
        const {navigate} = this.props.navigation;
        navigate('FriendsList',{groupName:this.state.groupName,groupId:this.state.id,token:$this.state.token,groupList:$this.state.allList,getData:()=>{
            $this.getMembers();
        }})
    }

    getMembers(){
        // alert(this.state.id)
        var $this = this;
        userService.groupUserQuery(function(data){
            if(data.code==10000){
                // alert(JSON.stringify(data));
                $this.selectData(data.data);
            }
        },/*3*/$this.state.id,$this.state.token)
    }

    selectData(arr){
        var len = arr.length;
        var obj = {};
        var managerArr = [];
        var list = [];
        for(var i=0;i<len;i++){
            if(arr[i].role==1){
                obj = arr[i];
            }else if(arr[i].role==2){
                managerArr.push(arr[i]);
            }else{
                list.push(arr[i]);
            }
        }
        this.list = list;
        this.setState({
            memberList:this.state.memberList.cloneWithRows(list),
            groupUser:obj,
            managerList:managerArr,
            allList:arr,
            listStaturs:list.length>0?true:false
        })
    }
    //设置管理员
    setManager(id,type,index){
        var $this = this;
        userService.operateUsers(function(data){
            // alert(JSON.stringify(data));
            if(data.code==10000){
                $this.changeList(index);
                alert('设置成功！');
            }
        },id,$this.state.id,type,$this.state.token)
    }
    //点编辑以后的操作改变列表结构
    changeList(num){
        if(this.state.addManagerStaturs){
            var managerArr = this.state.managerList;
            var list = this.list;
            managerArr.push(list[num]);
            this.list.splice(num,1);
            this.list = JSON.parse(JSON.stringify(this.list));
            this.setState({
                memberList:this.state.memberList.cloneWithRows(this.list),
                managerList:managerArr,
                listStaturs:this.list.length>0?true:false
            })  
        }else if(this.state.deleteManager){
            var managerArr = this.state.managerList;
            this.list.push(managerArr[num]);
            managerArr.splice(num,1);
            this.setState({
                memberList:this.state.memberList.cloneWithRows(this.list),
                managerList:managerArr,
                listStaturs:this.list.length>0?true:false
            })
        }else if(this.state.deleteMember){
            this.list.splice(num,1);
            this.list = JSON.parse(JSON.stringify(this.list));
            this.setState({
                memberList:this.state.memberList.cloneWithRows(this.list),
                listStaturs:this.list.length>0?true:false
            })
        }
    }

    searchMember(text){
        this.setState({
            searchText:text
        })
        if(text.replace(/^\s$/g,'')==''){
            this.selectData(this.state.allList);
        }
        
    }
    
    searchResult(){
        var text = this.state.searchText.replace(/^\s$/g,'');
        if(text!=''){
            var user = {};
            var managerArr = [];
            var list = [];
            var managerLen = this.state.managerList.length;
            var listLen = this.list.length;
            if(this.state.groupUser.username.indexOf(text)!=-1){
                user = this.state.groupUser;
            }
            for(var i=0;i<managerLen;i++){
                if(this.state.managerList[i].username.indexOf(text)!=-1){
                    managerList.push(this.state.managerList[i]);
                }
            }
            for(var j=0;j<listLen;j++){
                if(this.list[j].username.indexOf(text)!=-1){
                    list.push(this.list[j]);
                }
            }
            this.list = list;
            this.setState({
                memberList:this.state.memberList.cloneWithRows(list),
                groupUser:user,
                managerList:managerArr,
                listStaturs:list.length>0?true:false
            })
            if(!user.username && list.length==0 && managerArr.length==0){
                alert('未找到该用户！');
                this.selectData(this.state.allList);
            }
        }
        
    }

    editList(){
        this.setState({
            modalVisible:true
        })
    }
    closeModal(){
        this.setState({
            modalVisible:false
        })
    }

    selectModal(key){
        if(key==1){
            var list = JSON.parse(JSON.stringify(this.list));
            this.setState({
                addManagerStaturs:true,//添加管理员
                deleteManager:false,//删除管理员
                deleteMember:false,//删除群成员
                addMember:false,//添加群成员
                memberList:this.state.memberList.cloneWithRows(list),
            })
        }else if(key==2){
            var list = JSON.parse(JSON.stringify(this.list));
            this.setState({
                addManagerStaturs:false,//添加管理员
                deleteManager:true,//删除管理员
                deleteMember:false,//删除群成员
                addMember:false,//添加群成员
                memberList:this.state.memberList.cloneWithRows(list),
            })
        }else if(key==3){
            var list = JSON.parse(JSON.stringify(this.list));
            this.setState({
                addManagerStaturs:false,//添加管理员
                deleteManager:false,//删除管理员
                deleteMember:true,//删除群成员
                addMember:false,//添加群成员
                memberList:this.state.memberList.cloneWithRows(list),
            })
        }else if(key==4){
            var list = JSON.parse(JSON.stringify(this.list));
            this.setState({
                addManagerStaturs:false,//添加管理员
                deleteManager:false,//删除管理员
                deleteMember:false,//删除群成员
                addMember:true,//添加群成员
                memberList:this.state.memberList.cloneWithRows(list),
            })
            this.goFriendsList();
        }else{
            var list = JSON.parse(JSON.stringify(this.list));
            this.setState({
                addManagerStaturs:false,//添加管理员
                deleteManager:false,//删除管理员
                deleteMember:false,//删除群成员
                addMember:true,//添加群成员
                memberList:this.state.memberList.cloneWithRows(list),
            })
        }
        this.closeModal();
    }


}

class MemberItem extends Component{

    render(){
        return(
            <View style={{flexDirection:'row',alignItems:'center',paddingLeft:10,paddingRight:10,backgroundColor:'#fff',paddingTop:5,paddingBottom:5,flex:1}}>
                <ImageWrapper style={{borderRadius:3}} icon={this.props.icon} width={50} height={50}/>
                <Text style={{color:'#333',fontSize:18,marginLeft:10}}>{this.props.name}</Text>
                <ImageWrapper icon={'v'} width={16} height={16} style={{marginLeft:5}}/>
                <Text style={{fontFamily:'symbol',color:'#f4ea2a',fontSize:18}}>{this.props.rank}</Text>
            </View>
        )
    }
}

const styles = StyleSheet.create({
    container:{
        flex:1,
        backgroundColor:'#EFEFF4',
        ...Platform.select({
            ios: {
                marginTop: 20
            },
            android: {
                marginTop:0
            },

        }),
    },
    listTitle:{
    	height:30,
    	justifyContent:'center',
    	paddingLeft:5,
    	paddingLeft:5
    },
    modalBox:{
        flex:1,
        alignItems:'center',
        justifyContent:'flex-end',
        backgroundColor:'rgba(3,3,3,.2)',
    },
    modalList:{
        height:40,
        width:width-20,
        alignItems:'center',
        justifyContent:'center',
        backgroundColor:'#fff',
    },
    borderLine:{
        borderBottomWidth:1,
        borderBottomColor:'#ccc'
    }
    
    
});